<template>
  <div class="login-container">
    <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left" label-width="0px" class="card-box login-form"
      v-loading.fullscreen.lock="fullscreenLoading">
      <h3 class="title">洞见云 运营管理系统</h3>
      <el-form-item prop="username">
        <span class="svg-container svg-container_login">
          <svg-icon icon-class="user" />
        </span>
        <el-input name="username" type="text" v-model="loginForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"></svg-icon>
        </span>
        <el-input name="password" :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.password" placeholder="请输入密码"></el-input>
        <span class="show-pwd" @click="showPwd">
          <svg-icon icon-class="eye" />
        </span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width:100%;" :loading="loading" @click.native.prevent="handleLogin">登 录</el-button>
      </el-form-item>
    </el-form>
    <div class="bottom_info">
      <span>© 2019 I3020.com 版权所有 ICP证：浙15043253号-1</span><br>
      <span>浙公网安备33010602001421号</span><img @click="goCopyright" src="../../assets/images/icon-police.png">
    </div>
    <el-dialog custom-class="default_store_dialog" :visible.sync="dialogVisibleOrg" :fullscreen="true" :modal="false" :close-on-click-modal="false"
      :show-close="false">
      <el-container style="height: calc(100vh - 40px);">
        <el-container>
          <el-main style="background:#f5f5f5">
            <div class="all_store">
              <div>{{org_hint}}</div>
              <el-row class="store_list" style="margin-top:30px;display: inline-block;max-width:80%">
                <el-col :span="6" class="store_col" style="min-width:340px" v-for="item of orgList" :key="item.id">
                  <div @click="selectPlatOrg(item)" class="store_item">
                    <div class="text">
                      <div class="name">
                        <div style="margin: 0 auto;">{{item.name}}</div>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-main>
        </el-container>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
import md5 from 'js-md5';
import { isvalidUsername } from '@/utils/validate';
import { JSEncrypt } from 'jsencrypt';
import { login, get_routes, getEmpPlatOrg } from '@/api/login';
import { setToken } from '@/utils/auth';
export default {
  name: 'login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('请输入正确的用户名'));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能小于6位'));
      } else {
        callback();
      }
    };
    return {
      public_key:
        '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3//sR2tXw0wrC2DySx8vNGlqt3Y7ldU9+LBLI6e1KS5lfc5jlTGF7KBTSkCHBM3ouEHWqp1ZJ85iJe59aF5gIB2klBd6h4wrbbHA2XE1sq21ykja/Gqx7/IRia3zQfxGv/qEkyGOx+XALVoOlZqDwh76o2n1vP1D+tD3amHsK7QIDAQAB-----END PUBLIC KEY-----',
      routes: [],
      platform: [],
      dialogVisible: false,
      data: null, //登录数据
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePass }]
      },
      loading: false,
      fullscreenLoading: false,
      pwdType: 'password',
      org_name: '',
      org_hint: '检测到您有加入多个组织，请选择一个后进入系统',
      dialogVisibleOrg: false,
      orgList: []
    };
  },
  methods: {
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = '';
      } else {
        this.pwdType = 'password';
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          let encryptor = new JSEncrypt();
          encryptor.setPublicKey(this.public_key);
          let data = {
            name: this.loginForm.username,
            pwd: encryptor.encrypt(md5(this.loginForm.password)),
            pwd_len: this.loginForm.password.length,
            captcha: ''
          };
          login(data)
            .then(res => {
              this.platform = [];
              if (res.code == 1) {
                this.data = res.data;
                let obj = res.choose_beauty;
                if (obj == '') {
                  this.$message.error('没有权限');
                  this.loading = false;
                  return;
                }
                setToken(res.dixueshengka);
                sessionStorage.setItem('SMS_GiftDisplay', '1');
                localStorage.setItem('USER_INFO', JSON.stringify(res.data));
                localStorage.setItem('AUTH_ROUTER', JSON.stringify([])); //清空路由
                localStorage.setItem('SIDEBAR', JSON.stringify([]));
                this.$store.commit('updateorgid', 0);
                if (res.data.default_store != null) {
                  this.$store.commit('updateopid', res.data.default_store);
                }
                this.getEmpPlatOrg();
              }
            })
            .catch(res => {
              this.loading = false;
            });
        }
      });
    },
    getEmpPlatOrg() {
      getEmpPlatOrg().then(res => {
        if (res && res.length > 0) {
          this.orgList = res;
          if (res.length == 1) {
            let item = res[0];
            this.$store.commit('updateorgid', item.id);
            localStorage.setItem('orgName_' + this.data.id, item.name);
            this.org_name = item.name;
            this.dialogVisibleOrg = false;
            this.getRoutes();
          } else {
            // 等待用户选择
            this.dialogVisibleOrg = true;
          }
        } else {
          this.dialogVisibleOrg = true;
          this.orgList = [];
          // 无任何组织的访问权限
          this.org_hint = '您当前没有加入任何组织，请联系管理员加入';
        }
      });
    },
    selectPlatOrg(item) {
      this.$store.commit('updateorgid', item.id);
      localStorage.setItem('orgName_' + this.data.id, item.name);
      this.org_name = item.name;
      this.dialogVisibleOrg = false;
      this.getRoutes();
    },
    goCopyright() {
      window.open('http://www.beian.gov.cn/portal/registerSystemInfo?spm=5176.12901015.7y9jhqsfz.28.500f525cFgQQpc');
    },
    getRoutes(response) {
      get_routes({ uid: this.data.id })
        .then(response => {
          //获取路由权限树数据，转换格式后存储至localStorage
          var auths = response.list;
          var routelist = [];
          for (let i = 0; i < auths.length; i++) {
            routelist[i] = {};
            routelist[i].id = auths[i].id * 1;
            routelist[i].parent_id = auths[i].parent_id * 1;
            routelist[i].is_del = auths[i].is_del * 1;
            routelist[i].name = auths[i].name;
            routelist[i].router_hidden = auths[i].rou_hidden * 1;
            routelist[i].router_layout = auths[i].rou_layout * 1;
            routelist[i].router_order = auths[i].rou_order * 1;
            routelist[i].router_meta_icon = auths[i].rou_meta_icon;
            if (auths[i].rou_path == '') {
              routelist[i].router_name = auths[i].rou_name;
              routelist[i].router_path = auths[i].rou_name;
              routelist[i].router_component = auths[i].rou_comp_exist == 1 ? auths[i].rou_name : '';
            } else if (auths[i].rou_path == '/') {
              routelist[i].router_name = auths[i].rou_name;
              routelist[i].router_path = '/' + auths[i].rou_name;
              routelist[i].router_component = auths[i].rou_comp_exist == 1 ? auths[i].rou_name : '';
            } else {
              routelist[i].router_name = auths[i].rou_path + '/' + auths[i].rou_name;
              routelist[i].router_path = auths[i].rou_name;
              routelist[i].router_component = auths[i].rou_comp_exist == 1 ? routelist[i].router_name : '';
            }
            if (auths[i].rou_path_arg != '') {
              routelist[i].router_path += '/' + auths[i].rou_path_arg;
            }
          }
          // 数据库索引排序
          routelist = routelist.sort(function(a, b) {
            if (a.router_order > b.router_order) {
              return -1;
            } else if (a.router_order < b.router_order) {
              return 1;
            } else {
              return 0;
            }
          });
          localStorage.setItem('AUTH_ROUTER', JSON.stringify(routelist));
          this.fullscreenLoading = false;
          //这个reload的非常关键，它会让整个APP重启，从而重新加载路由（这个时候从缓存中取出登录成功后获得的路由权限数据）
          location.reload();
        })
        .catch(res => {
          this.loading = false;
        });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
@import 'src/styles/login.scss';
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
.show-pwd {
  display: none;
}
.djlogo {
  position: absolute;
  top: 30px;
  left: 30px;
  height: 30px;
}
.platform_title {
  margin-top: 20vh;
  text-align: center;
  margin-bottom: 40px;
  font-size: 18px;
  color: #000;
  font-weight: normal;
}
.platform {
  margin: 0 auto;
  margin-top: 20px;
  display: flex;
  justify-content: center;
  .platform_item {
    padding: 50px 30px;
    font-size: 18px;
    color: #fff;
    background: #3e6fab;
    border: 1px solid #3e6fab;
    border-radius: 5px;
    cursor: pointer;
    box-shadow: 4px 5px 10px #3e6fab;
  }
  .platform_item + .platform_item {
    margin-left: 60px;
  }
}
</style>